package zheezes.util;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @author hcconquer@gmail.com
 */
public class ZInputStream {
	public static int waitFor(InputStream in, int msec) {
		int sleep = msec / 100;
		if (sleep < 10) {
			sleep = 10;
		}
		for (int time = 0; time < msec; time += sleep) {
			int num = -1;
			try {
				num = in.available();
			} catch (IOException e) {
			}
			if (num > 0) {
				return num;
			}
			ZThread.msleep(sleep);
		}
		return -1;
	}
	
	public static String toString(InputStream in) {
		return new String(readEx(in));
	}
	
	public static InputStream getInputStream(byte[] bytes) {
		if (bytes == null) {
			return null;
		}
		return new ByteArrayInputStream(bytes);
	}
	
	public static final byte[] read(InputStream in) throws IOException {
		InputStream input = new BufferedInputStream(in);
		List<byte[]> buflist = new ArrayList<byte[]>();
		byte[] buffer = new byte[512];
		int len = -1, sum = 0;
		while ((len = input.read(buffer)) != -1) {
			byte[] buf = new byte[len];
			System.arraycopy(buffer, 0, buf, 0, len);
			buflist.add(buf);
			sum += len;
		}
		buffer = new byte[sum];
		int pos = 0;
		for (byte[] buf: buflist) {
			System.arraycopy(buf, 0, buffer, pos, buf.length);
			pos += buf.length;
		}
		return buffer;
	}
	
	public static final byte[] readEx(InputStream in)  {
		try {
			return read(in);
		} catch (IOException e) {
		}
		return null;
	}
}
